package crazyFace.system.app;
import android.graphics.Canvas;

public class GameLoopThread extends Thread {
	static final long FPS = 10;
	private GameView view;
	private boolean running = false;
      
	public GameLoopThread(GameView view) {
		this.view = view;
	}
 
	public void setRunning(boolean run) {
		running = run;
	}
       
	public void kill(){
		running = false;
	}

	public void run() {
		long frameLength = 1000 / FPS;
		long startingTime;
		long sleepTime;
		
		while (running) {
			Canvas canvas = null;
			startingTime = System.currentTimeMillis();
			try {
				canvas = view.getHolder().lockCanvas();
				synchronized (view.getHolder()) {
					if(canvas != null){
						view.onDraw(canvas);
					}
				}
			} finally {
				if (canvas != null) {
					view.getHolder().unlockCanvasAndPost(canvas);
				}
			}
			sleepTime = frameLength - (System.currentTimeMillis() - startingTime);
			try {
				if (sleepTime > 0)
					sleep(sleepTime);
				else
					sleep(15);
             	} catch (Exception e) {}
			
		}
	}
}